package com.htfyun.ft.agingtest;

import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.PowerManager;

import com.htfyun.ft.R;
import com.htfyun.ft.common.SettingsUtils;
import com.htfyun.ft.utils.DebugLog;
import com.htfyun.ft.utils.TimeStringUtils;

public class TestSleep extends AgingTestItemBase {

    private final static String SLEEP_ACTION = "com.rockchip.sleep.ACTION_TEST_CASE_SLEEP";

    private final long AWAKE_TIME = 5000L;
    private final long SLEEP_TIME = 20000L;

    private final int SCREEN_OFF_TIME = 15000;


    @Override
    protected void doStartTest() {

        DebugLog.e("TestSleep doStartTest");

        IntentFilter filter = new IntentFilter(SLEEP_ACTION);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        getContext().registerReceiver(sleepTestReceiver, filter);

        startTestSleep();
    }

    @Override
    protected void doStopTest() {

        DebugLog.e("TestSleep doStopTest");

        turnOnScreen();
        stopAlarm();
        getContext().unregisterReceiver(sleepTestReceiver);

        SettingsUtils.setScreenOffTimeForFT(getContext());
    }

    @Override
    public AgingTestItemAttr getAgingTestItemAttr() {
        return AgingTestItemAttr.sleep;
    }

    @Override
    public CharSequence getInfoString() {

        final long usedTime = AgingLongSettingsAttr.aging_time_tick.get() - getAgingTestItemAttr().getStartTime_ms();
        final String timeStr = TimeStringUtils.makeTimeString(usedTime);

        return getContext().getString(R.string.aging_sleep_info,
                SCREEN_OFF_TIME / 1000,
                SLEEP_TIME / 1000, getAgingTestItemAttr().getTestCount(),
                timeStr);
    }

    @Override
    public boolean needKeepScreenOn(){
        return false;
    }

    private void startTestSleep() {

        stopAlarm();

        try {
            SettingsUtils.setScreenOffTime(getContext(), SCREEN_OFF_TIME);
            setAlarm(SLEEP_TIME, true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setAlarm(long intervalMillis, boolean repeat) {
        AlarmManager alarmManager = (AlarmManager) getContext()
                .getSystemService(Context.ALARM_SERVICE);

        if (alarmManager == null) {
            return;
        }

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getContext(), 0, new Intent(SLEEP_ACTION), 0);

        if (repeat) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    intervalMillis + System.currentTimeMillis(), intervalMillis,
                    pendingIntent);
        }
    }

    private void stopAlarm() {

        PendingIntent localPendingIntent = PendingIntent.getBroadcast(
                getContext(), 0, new Intent(SLEEP_ACTION), 0);
        AlarmManager alarmManager = ((AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE));

        if (alarmManager != null) {
            alarmManager.cancel(localPendingIntent);
        }
    }


    private BroadcastReceiver sleepTestReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context mContext, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            DebugLog.e("SleepTestReceiver onReceive, action = " + action);

            if (action.equals(SLEEP_ACTION)) {
                getAgingTestItemAttr().addOneTestCount();

                turnOnScreen();

            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
            }
        }
    };

    private void turnOnScreen() {
        PowerManager pw = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
        if (pw != null) {
            pw.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                    "factoryTest:ScreenOnTimer").acquire(AWAKE_TIME);
        }

        KeyguardManager km = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
        if (km != null) {
            km.newKeyguardLock("TestSleep").disableKeyguard();
        }
    }

}
